import React, { Component } from 'react';

class Index extends Component {
    constructor(props) {
        super(props)
        this.state = {
            list:JSON.parse(localStorage.getItem("class"))|| [],
            msg: ""
        }
    }
    render() {
        const ListItem = this.state.list.map((item, index) => {
            if (item.checked === false) {
                return (
                    <div key={item.id}>
                        <input type="checkbox" name="" id="" checked={item.checked} onChange={this.toChange.bind(this, index)} />
                        {item.msg}
                        <button onClick={this.toDelete.bind(this, index)}>删除</button>
                    </div>
                )
            }
        })
        const DoneItem = this.state.list.map((item, index) => {
            if (item.checked === true) {
                return (
                    <div key={item.id}>
                        <input type="checkbox" name="" id="" checked={item.checked} onChange={this.toChange.bind(this, index)} />
                        {item.msg}
                        <button onClick={this.toDelete.bind(this, index)}>删除</button>
                    </div>
                )
            }
        })
        return (
            <div>
                <h1>TodoList</h1>
                <input type="text" onChange={this.handleChange} value={this.state.msg} onKeyUp={this.toDo} />
                <h2>进行中</h2>
                {ListItem}
                <h2>已完成</h2>
                {DoneItem}
            </div>
        );
    }
    handleChange = (e) => {
        this.setState({ msg: e.target.value })
    }
    toDo = (e) => {
        if (e.keyCode == 13) {
            var obj = {
                msg: e.target.value,
                checked: false,
                id: Math.random(),
            };
            var list = this.state.list;
            var s = list.findIndex((item) => item.msg === obj.msg);
            if (s === -1&&obj.msg!='') {
                list.unshift(obj);
            }
            this.state.msg = "";
            this.local();
            this.setState({
                list
            })
        }
    }
    toChange = (index) => {
        var list = this.state.list;
        list[index].checked = !list[index].checked;
        this.local();
        this.setState({
            list
        })
    }
    toDelete = (val) => {
        var list = this.state.list
        list.splice(val, 1);
        this.local();
        this.setState({
            list
        })
    }
    local = () => {
        var list = this.state.list;
        localStorage.setItem("class", JSON.stringify(list))
    }
}

export default Index;
